package com.yang.inventorymanagement.controllerview.products;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yang.inventorymanagement.comment.TableComponent;
import com.yang.inventorymanagement.pojo.Inventory;
import com.yang.inventorymanagement.pojo.Products;
import com.yang.inventorymanagement.service.InventoryService;
import com.yang.inventorymanagement.service.ProductsService;
import com.yang.inventorymanagement.utils.SessionUtils;
import com.yang.inventorymanagement.utils.SpringContextUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;

@Lazy
@Component("ProductsNumberManageSwing")
@Scope("prototype")
/**
 * 库存管理
 */
public class ProductsNumberManageSwing extends JDialog {

    private JTextField suppliersId;
    private JTextField suppliersName;

    private JTextField suppliersNumber;

    private JTextField productId;

    private TableComponent table;

    private JPanel contentPane;


    // 表格数据
    private Object[] columnNames = {"商品编号", "商品名称", "商品总库存", "供应商识别代码", "供应商名称", "供应商库存"};
    private Object[][] rowData;

    //商品service
    private ProductsService productsService = SpringContextUtils.getBean(ProductsService.class);
    //库存service
    private InventoryService inventoryService = SpringContextUtils.getBean(InventoryService.class);


    public ProductsNumberManageSwing() {
        Map<String, Object> session = SessionUtils.getSession();
        String integer = SessionUtils.getSession().get("productsId").toString();
        String suppliersIdSession = integer.toString();
        setModal(true);
        setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        //设置窗口大小
        setBounds(0, 0, 800, 700);
        //设置居中显示
        setLocationRelativeTo(null);
        //设置不可编辑
        setResizable(false);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        Border titleBorder = BorderFactory.createTitledBorder("库存管理");
        contentPane.setBorder(titleBorder);
        setContentPane(contentPane);

        JLabel jLabel = new JLabel("库存管理");
        jLabel.setBounds(210, 10, 142, 32);
        jLabel.setFont(new Font("宋体", Font.PLAIN, 24));

        /**
         * 刷新按钮
         */


        JPanel suppliersListPanel = new JPanel();
        suppliersListPanel.setBorder(BorderFactory.createTitledBorder("商品库存列表"));
        suppliersListPanel.setBounds(10, 54, 746, 661);
        add(suppliersListPanel);

        // 设置表格数据 假数据
        rowData = productsService.getAllProductsAndSuppliers(Integer.valueOf(integer));


        // 创建一个表格，指定 所有行数据 和 表头
        table = new TableComponent(rowData, columnNames);
        suppliersListPanel.add(table.getTableHeader());                        // 添加表头
        suppliersListPanel.setLayout(new BorderLayout(5, 5));
        JScrollPane scrollPane = new JScrollPane(table);                // 将表格添加到滚动面板中
        suppliersListPanel.add(scrollPane);


// 商品信息管理界面
        // 商品信息管理界面
        JPanel productsMsgPanel = new JPanel();
        productsMsgPanel.setBorder(BorderFactory.createTitledBorder("商品库存管理"));
        productsMsgPanel.setBounds(766, 54, 389, 661);
        add(productsMsgPanel);

// 设置布局管理器为GridBagLayout
        productsMsgPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = GridBagConstraints.REMAINDER;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JLabel lblid = new JLabel("供应商识别码");
        productsMsgPanel.add(lblid, gbc);

        suppliersId = new JTextField();
        suppliersId.setVisible(true);
        suppliersId.setEnabled(false);
        suppliersId.setColumns(10);
        productsMsgPanel.add(suppliersId, gbc);

        JLabel label_3 = new JLabel("供应商名称");
        productsMsgPanel.add(label_3, gbc);

        suppliersName = new JTextField();
        suppliersName.setVisible(true);
        suppliersName.setEnabled(false);
        productsMsgPanel.add(suppliersName, gbc);


        JLabel label_4 = new JLabel("供应商库存");
        productsMsgPanel.add(label_4, gbc);

        suppliersNumber = new JTextField();
        suppliersNumber.setVisible(true);
        productsMsgPanel.add(suppliersNumber, gbc);

        productId = new JTextField();
        //不可见
        productId.setVisible(false);
        productsMsgPanel.add(productId, gbc);

        JButton suppliersNumberButton = new JButton("库存修改");
        productsMsgPanel.add(suppliersNumberButton);
        /**
         * 库存修改按钮
         */
        suppliersNumberButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //供应商id
                Integer suppliersIdText = Integer.valueOf(suppliersId.getText());
                //商品id
                Integer productIdText = Integer.valueOf(productId.getText());
                //供应商库存
                Integer suppliersNumberText = Integer.valueOf(suppliersNumber.getText());

                if (!suppliersNumber.getText().matches("\\d+")) {
                    JOptionPane.showMessageDialog(null, "填写错误，请重新填写", "提示", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                if (suppliersNumberText < 0) {
                    JOptionPane.showMessageDialog(null, "填写错误，请重新填写", "提示", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                QueryWrapper<Inventory> inventoryQueryWrapper = new QueryWrapper<>();
                inventoryQueryWrapper.eq("SupplierID", suppliersIdText);
                inventoryQueryWrapper.eq("ProductID", productIdText);
                Inventory inventory = inventoryService.getOne(inventoryQueryWrapper);
                //原来的库存
                Integer quantity = inventory.getQuantity();
                //现在的数量  原来的库存-输入框库存
                Integer nowNumber = suppliersNumberText - quantity;
                //修改商品总数量
                Products productsServiceById = productsService.getById(productIdText);
                Products products = new Products();
                products.setProductid(productIdText);
                products.setQuantity(productsServiceById.getQuantity() + nowNumber);
                boolean b = productsService.updateById(products);
                boolean flag = false;
                if (b) {
                    inventory.setQuantity(suppliersNumberText);
                    flag = inventoryService.updateById(inventory);
                }
                if (flag) {
                    JOptionPane.showMessageDialog(null, "库存更新成功", "提示", JOptionPane.INFORMATION_MESSAGE);
                    clearField();
                    return;
                } else {
                    JOptionPane.showMessageDialog(null, "库存更新失败", "提示", JOptionPane.ERROR_MESSAGE);
                    return;
                }


            }
        });

        JButton flash = new JButton("刷新数据");
        productsMsgPanel.add(flash);
        flash.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                updateProductsList(0, integer);
            }
        });

        /**
         * 监控表格
         */
        ListSelectionModel selectionModel = table.getSelectionModel();
        selectionModel.addListSelectionListener(new ListSelectionListener() {
            // 会响应两次，使用e.getValueIsAdjusting()判断，鼠标点击，getValueIsAdjusting() 返回True.
            // 鼠标释放,getValueIsAdjusting() 返回 False
            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting()) {
                    String str = e.getSource().toString();
                    // 取出当前行
                    String indexStr = str.substring(str.lastIndexOf("{") + 1, str.lastIndexOf("}"));
                    if (str != null && !"".equals(str.trim()) && indexStr != null && !"".equals(indexStr.trim())) {
                        // 获取当前行序号
                        int index = Integer.parseInt(indexStr);
                        Integer supplierrId = (Integer) rowData[index][3];
                        String supplierrName = (String) rowData[index][4];
                        Integer supplierrNumber = (Integer) rowData[index][5];
                        Integer productIds = (Integer) rowData[index][0];

                        // 封装数据
                        suppliersId.setText(supplierrId.toString());
                        suppliersName.setText(supplierrName);
                        suppliersNumber.setText(String.valueOf(supplierrNumber));
                        productId.setText(String.valueOf(productIds));


                    }
                }
            }
        });


    }


    private void updateProductsList(int type, String input) {
        productsService.getAllproducts();
        if (type == 0) rowData = productsService.getAllProductsAndSuppliers(Integer.valueOf(input));
        table.updateModel(rowData, columnNames);
        clearField();
    }
    /**
     * 清空输入框数据
     */
    private void clearField() {
        suppliersId.setText("");
        suppliersName.setText("");
        suppliersNumber.setText("");
        productId.setText("");

    }
}
